<template>
  <div>
    <el-card class="box-card">
      <!-- 头像 -->
      <div class="img-box">
        <img class="img" src="@/assets/img/avatar.jpg" alt="" v-if="!avatar" />
        <img class="img" :src="avatar" alt="" v-else />
      </div>
      <div class="btn-upload">
        <input type="file" name="" id="" style="display: none" ref="iptRef" @change="onFlieChange" />
        <el-button type="primary" @click="chooseImg"><i class="el-icon-plus"></i>选择图片</el-button>
        <el-button type="success" @click="uploadAvatarFn"><I class="el-icon-upload">上传头像</I></el-button>
      </div>
    </el-card>
  </div>
</template>
<script setup>
import { getCurrentInstance, ref } from 'vue'
import { uploadAvatar } from '@/api/index.js'
import { userinfo } from '@/store/index.js'
const avatar = ref('')
const iptRef = ref()
const chooseImg = () => {
  iptRef.value.click()
}
const { proxy } = getCurrentInstance()
// 选择图片确定
const onFlieChange = e => {
  const files = e.target.files // 拿到用户选择的文件数组
  if (files.length === 0) {
    // 判断文件数组的长度0没有选择
    avatar = ''
  } else {
    // this.avatar = URL.createObjectURL(files[0])
    if (files[0].type.startsWith('image')) {
      if (files[0].size / 1024 / 1024 >= 10) {
        proxy.$Message({
          type: 'warning',
          message: '上传的图片不能超过10M'
        })
        return
      }
      const fr = new FileReader()
      fr.readAsDataURL(files[0]) // 传入文件对象开始阅读
      fr.onload = e => {
        // onlad等待把文件读成base64字符串后会触发onload时间函数
        // e.target.result的值就是读完的结果
        avatar.value = e.target.result
      }
    } else {
      proxy.$Message({
        type: 'warning',
        message: '只接受图片！'
      })
    }
  }
}
const userinfoStore = userinfo()
const uploadAvatarFn = () => {
  if (avatar.value !== '' && avatar.value !== null) {
    uploadAvatar(avatar.value).then(res => {
      if (!res.data) {
        proxy.$Message.error(res.msg)
        return
      }
      userinfoStore.profile.avatar = avatar.value
      proxy.$Message({
        type: 'success',
        message: res.msg
      })
    })
  }
}
</script>
<style lang="less" scoped>
.btn-upload {
  margin-top: 8px;
}
.img-box {
  width: 350px;
  height: 350px;
  border: 1px solid pink;
  .img {
    width: 350px;
    height: 350px;
    object-fit: cover;
  }
}
</style>